import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Toast, Dialog, TextArea } from 'antd-mobile'
import HeadTop from '@/components/HeadTop';
import InfoList from '@/components/InfoList';
import FootButton from '@/components/FootButton';
import CheckItems from '@/components/CheckItems';
import UploadPhotos from '@/components/UploadPhotos';
import Loading from '@/components/Loading';

import Index from '@/api/spotCheck';
import { add_check_cache, decrement_check_cache, change_spot_params } from '@/Store/action';
import { connect } from 'react-redux';
import { infoFields } from '../_parts/const';
import "./index.less"

function Detail(props) {
    const [loading, setLoading] = useState(false);
    const [detaiObj, setDetaiObj] = useState({ itemVoList: [] });
    const [sureButtonTxt, setSureButtonTxt] = useState("开始巡检")
    const uploadRef = useRef()
    const detailRef = useRef(detaiObj)
    const navigate = useNavigate(); // 替换useHistory
    const location = useLocation(); // 新增location获取

    useEffect(() => { getInfoDetail() }, []);

    useEffect(() => {
        if (location.key !== 'default' && location.state?.from !== 'Inspection') {
            changeCache('add_check_cache')
        }
    }, [location]);

    const changeCache = (type) => {
        let oc = {
            no: detailRef.current.no,
            items: detailRef.current.itemVoList
        }
        props[type](oc)
    }


    const getInfoDetail = async () => {
        setLoading(true)
        let res = await Index.loadByNo(props.location.state.no)
        const result = res.data
        if (result.code) {
            Toast.show({
                content: '请求失败:' + result.msg,
            })
            return
        }
        // 获取缓存check cache
        let rdata = JSON.parse(JSON.stringify(result.data));
        if(rdata.itemVoList?.length){
            if (result.data.status == 'PROCESSING') {
                rdata.itemVoList.forEach( el=> el.inspectionResult = '')
            }
        }
        let _data = getFilterCache(rdata)
        setDetaiObj(_data)
        detailRef.current = _data
        uploadRef.current && uploadRef.current.setPhotoListFinish(result.data?.photoUrl || [])
        if (result.data.status == 'PROCESSING') {
            setSureButtonTxt("完成巡检")
        }
        setLoading(false)
    }

    const getFilterCache = (data) => {
        let o = data
        if (props.checkItemsCache.length) {
            let c = props.checkItemsCache.findIndex(el => el.no == data.no)
            if (c > -1) {
                o = {
                    ...data,
                    itemVoList: props.checkItemsCache[c].items
                }
            }
        }

        return o
    }


    const getSubmitSure = () => {
        let txt = detaiObj.status == 'WAIT_FINISH' ? '确定开始巡检' : '确定完成巡检'
        if (txt == '确定完成巡检') {
            let noCheck = []
            detaiObj.itemVoList.forEach((el, index) => {
                if (!el.inspectionResult) {
                    noCheck.push(index + 1)
                }
            })
            if (noCheck.length) {
                Toast.show({
                    content: `第${noCheck.join(" ")}项未选择`,
                })
                return
            }
        }
        Dialog.confirm({
            content: txt,
            onConfirm: () => {
                handleSubmit()
            },
        })
    }

    const handleSubmit = () => {
        if(detaiObj.status == 'PROCESSING'){
            // let noR = false
            // detaiObj.itemVoList.forEach( el=>{
            //     if(!el.inspectionResult){
            //         noR = true
            //     }
            // })
            // if(noR){
            //     Toast.show({
            //         content: '请选择检验结果!',
            //     })
            //     return
            // }

            if(uploadRef.current && uploadRef.current.photoList.join(",") < 1){
                Toast.show({
                    content: '请上传图片!',
                })
                return
            }

            let isN = detaiObj.itemVoList.some(el => {
                if (el.inspectionResult == 'UNQUALIFIED') {
                    return true
                }
                return false
            })
            if (isN) {
                Dialog.show({
                    content: '有不合格检验，是否需要维修',
                    closeOnAction: true,
                    actions: [
                        {
                            key: 'done',
                            text: '继续完成',
                        },
                        [
                            {
                                key: 'cancel',
                                text: '取消',
                            },
                            {
                                key: 'sure',
                                text: '去维修',
                            },
                        ],
                    ],
                    onAction: (actionKey) => handleDialogAction(actionKey.key),
                });
                
                return
            }


        }
        submitFn()

    }

    const handleDialogAction = (actionKey) => {
        if (actionKey === 'done') {
            submitFn()
        } else if (actionKey === 'cancel') {
            console.log('取消')
        } else if (actionKey === 'sure') {
            let params = {
                no: detaiObj.no,
                status: detaiObj.status,
                itemList: detaiObj.itemVoList,
                photoUrl: uploadRef.current ? uploadRef.current.photoList.join(",") : '',
                workNo: props.username,
                remark: detaiObj.remark,
            }

            props.change_spot_params(params)
            
            navigate("/equipmentAdd", {
                state: {
                    from: "Inspection",
                    no: detaiObj.no,
                    detaiObj: detaiObj
                }
            });
        }
    };


    const submitFn = () => {

        let params = {
            no: detaiObj.no,
            status: detaiObj.status,
            itemList: detaiObj.itemVoList,
            photoUrl: uploadRef.current ? uploadRef.current.photoList.join(",") : '',
            workNo: props.username,
            remark: detaiObj.remark,
        }
        let api = Index.startInspection
        if (detaiObj.status == 'PROCESSING') {
            api = Index.finishInspection
        }
        setLoading(true)
        api(params).then(res => {
            setLoading(false)
            if (res.data.code) {
                Toast.show({
                    content: '请求失败:' + res.data.msg,
                })
                return
            }
            Toast.show({
                content: '提交成功',
            })
            changeCache('decrement_check_cache')
            getInfoDetail()
        })
    }

    return (
        <div className='page-wrapper'>
            {
                loading ? <Loading></Loading> : null
            }
            <HeadTop title="设备巡检详情" history={props.history}></HeadTop>
            <div className="page-body">
                <InfoList detaiObj={detaiObj} infoFields={infoFields}></InfoList>
                <div className="result">
                    <div className="d-title">设备巡检项目</div>
                    {
                        detaiObj.itemVoList?.length ?
                            (detaiObj.itemVoList.map(el =>
                                <CheckItems
                                    key={el.no}
                                    info={el}
                                    detaiObj={detaiObj}
                                ></CheckItems>
                            )) :
                            <div className='no-detail-data'>暂无更多数据</div>
                    }
                </div>
                {
                    detaiObj.status !== 'WAIT_FINISH' ?
                        <>
                            <div className="photos">
                                <div className="d-title">设备点检图</div>
                                <UploadPhotos
                                    ref={uploadRef}
                                    detaiObj={detaiObj}
                                    showUpload="PROCESSING"
                                />
                            </div>
                            <div className="photos" style={{ marginTop: 15 }}>
                                <div className="d-title">备注</div>
                                <TextArea
                                    disabled={detaiObj.status == 'FINISH'}
                                    placeholder='请输入内容'
                                    value={detaiObj.remark}
                                    autoSize={{ minRows: 3, maxRows: 5 }}
                                    onChange={val => {
                                        setDetaiObj({
                                            ...detaiObj,
                                            remark: val
                                        })
                                    }}
                                />
                            </div>
                        </> : null
                }
            </div>
            {
                 (detaiObj.status == 'WAIT_FINISH' || detaiObj.status == 'PROCESSING') ?
                    <FootButton
                        cancelTxt="返回"
                        sureTxt={sureButtonTxt}
                        getSubmitCancel={() => props.history.goBack(-1)}
                        getSubmitSure={getSubmitSure}>
                    </FootButton> :
                    null
            }

        </div>
    );
}


const mapStateToProps = (state) => {
    return {
        checkItemsCache: state.checkItemsCache,
        username: state.username
    };
};

const mapDispatchToProps = {
    add_check_cache,
    decrement_check_cache,
    change_spot_params
};


export default connect(mapStateToProps, mapDispatchToProps)(Detail);
